<?php

/**
 * 
 * @author NutMotion <simonotm.linux@gmail.com> 
 */
require_once(dirname(__FILE__) . "/../commons/common-funcs.php");
require_once(dirname(__FILE__) . "/../db/common-operations.php");
require_once(dirname(__FILE__) . "/../db/associations.php");
require_once(dirname(__FILE__) . "/../db/bookmarksOperations.php");
require_once(dirname(__FILE__) . "/../db/tagsOperations.php");

function handleSearchTmp($request) {
//Format of the request
//bookmarks.php?action=read&req=ta,u,ti&res=ta,u,ti&crit=ta,u,ti&key=<keyword>

    /* Variable for tracking the state and data of the operation
     * ---------------------------------------------------------
     * Fields which are bound to be injected in the final ResultContext object are encapsulated inside a dedicated local variable.
     */

    //The state
    $success = false; //tracks the success or failure of the operation.
    //The data
    $arFeedbackMsg = array(); //stores feedback message(s) about the "unfolding" of this operation.
    $arReturnResults = array(); //stores the entities fetched from the Model layer.

    /* Additional variables for storing data
     * ---------------------------------------------------------
     */
//    $reqFields=$request['req'];
//    $resFields=$request['res'];
//    $criteria=$request['crit'];    
    $keywordFromQuery = $request['key']; // the "keyword" parameter from the Bookmarks-searchBySingleTag POST query.
    //$arMatchingTags
    //---------------
    //associative array which stores each tags which match the keyword.
    //Format:
    //$arMatchingTags["$tagId"]=array("id"=>"$tagId", "tag"=>$tag)
    $arMatchingTags = array();

    /* Misc variable for support
     * ---------------------------------------------------------
     */
    $arDbQueryResult;
    $nbTagsMatching = 0;

    /* There we go
     * ---------------------------------------------------------
     */

    connect(); //needed...


    /* Interactions with the Model layer
     * ---------------------------------------------------------
     */

    // 1) we check whether there's one (or more) tags which "tag" field matches the keyword.
    //SELECT id FROM webpage WHERE url='h'
    $arDbQueryResult = selectFromTable2("tags", "id,tag", "tag LIKE '%" . $keywordFromQuery . "%'", "tag");
    $countResultNb = count($arDbQueryResult);
    //Assumption: I'm not even sure about the format of the db rows returned by selectFromTable
    //assuming I'll get something like array(0=>array("id"=>"1"),1=>array("id"=>"2")) in case there's 2 results, for example.
    if ($countResultNb >= 0) {
        //we've found one or more tags which match the keyword : we add them to our $arMatchingTags temp array
        for ($i = 0; $i < $countResultNb; $i++) {

            $tagId = $arDbQueryResult[$i]["id"];
//            //we add it only IF it doesn't exist yet
            $arMatchingTags["$tagId"] = array("id" => "$tagId", "tag" => $arDbQueryResult[$i]["tag"]);
            $arReturnResults["default"][] = array("tag" => $arDbQueryResult[$i]["tag"]);
            $nbTagsMatching++;
            $success = true;
        }
    }

    return new ResultContext($success, $arReturnResults, $arFeedbackMsg);
}

function handleSearch($request) {
//Format of the request
//bookmarks.php?action=read&res=ta,u,ti&crit=ta,u,ti&key=<keyword>
    //this operation performs a join on the 3 tables
    //eg:
    //SELECT url, title, tag FROM webpage,tags,webpage_has_tags
    //WHERE webpage.id=webpage_has_tags.webpage_id 
    //AND tags.id=webpage_has_tags.tags_id
    //AND tags.tag LIKE '%prog%'
    //ORDER BY tag

    /* Variable for tracking the state and data of the operation
     * ---------------------------------------------------------
     * Fields which are bound to be injected in the final ResultContext object are encapsulated inside a dedicated local variable.
     */

    //The state
    $success = false; //tracks the success or failure of the operation.
    //The data
    $arFeedbackMsg = array(); //stores feedback message(s) about the "unfolding" of this operation.
    $arReturnResults = array(); //stores the entities fetched from the Model layer.

    /* Additional variables for storing data
     * ---------------------------------------------------------
     */
//    $reqFields=$request['req'];
    $fields = $request['fields'];
    $criteria = $request['crit'];
    $keyword = $request['key']; // the "keyword" parameter from the Bookmarks-searchBySingleTag POST query.
    //$arMatchingTags
    //---------------
    //associative array which stores each tags which match the keyword.
    //Format:
    //$arMatchingTags["$tagId"]=array("id"=>"$tagId", "tag"=>$tag)
    $arMatchingTags = array();

    /* Misc variable for support
     * ---------------------------------------------------------
     */
    $arDbQueryResult;
    $nbTagsMatching = 0;


    /*     * 1) we compute the request and result fields, to create the relevant SQL query part
     * 
     */

    //1a) we get the unabbreviated name for the fields
    $fields = replaceAbbreviations($fields);
    $criteria = replaceAbbreviations($criteria);


    //1b) we build the SQL query parts

    
    //array $fields. Used for sorting too    
    $sqlFields = "";
    $sortByField = ""; //we sort by fields in the same order as they've been passed through the request
    
    for ($i = 0; $i < count($fields); $i++) {
        if (strcasecmp($sqlFields, "") != 0) {
            $sqlFields.=",";
            $sortByField.=",";
        }
        $sqlFields.=$fields[$i];
        $sortByField.=$fields[$i];
    }

    //array $criteria
    $sqlCriteria = "(";
    for ($i = 0; $i < count($criteria); $i++) {
        if (strcasecmp($sqlCriteria, "(") != 0) {
            $sqlCriteria.=" OR ";
        }

        if (strcasecmp($criteria[$i], "url") == 0) {
            //url must be EXACT match
            $sqlCriteria.=$criteria[$i] . "='$keyword'";
        } else {
            //other fields are approximate
            $sqlCriteria.=$criteria[$i] . " LIKE '%$keyword%'";
        }
    }
    $sqlCriteria.=")";

    /* There we go
     * ---------------------------------------------------------
     */

    connect(); //needed...


    /* Interactions with the Model layer
     * ---------------------------------------------------------
     */

    /* 2) we just have to call the selectFromTable2 function
     * 
     */
    $arDbQueryResult = selectFromTable2("webpage,tags,webpage_has_tags", $sqlFields, "webpage.id=webpage_has_tags.webpage_id AND tags.id=webpage_has_tags.tags_id
            AND $sqlCriteria", $sortByField);

//print_r($arDbQueryResult);

    if (count($arDbQueryResult) > 0) {
        //there are matching results
        $success = true;
        $arReturnResults = array();

        for ($i = 0; $i < count($arDbQueryResult); $i++) {
//            $arReturnResults
        }
    }
    $arReturnResults["default"] = $arDbQueryResult;
    return new ResultContext($success, $arReturnResults, $arFeedbackMsg);
}

function replaceAbbreviations($abbreviations) {
    $extractedFields = "";
    $unabbreviated = explode(",", $abbreviations);

    if (($index = array_search("ta", $unabbreviated)) !== false) {
        //"ta" found
        $unabbreviated[$index] = "tag";
    }

    if (($index = array_search("u", $unabbreviated)) !== false) {
        $unabbreviated[$index] = "url";
    }

    if (($index = array_search("ti", $unabbreviated)) !== false) {
        $unabbreviated[$index] = "title";
    }

    return $unabbreviated;
}

/* * * Tests
 * 
 */

//$requestTests=array("fields"=>"ta,ti,u","crit"=>"ti","key"=>"mysql");
$requestTests = array("fields" => "ta", "crit" => "u", "key" => "http://dev.mysql.com/doc/refman/5.1/en/regexp.html");

//handleSearch($requestTests);
?>
